/*
 * Copyright (C) 2001-2005 Pleasant nightmare studio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.pleasantnightmare.noraxidium.util;

import org.apache.log4j.Logger;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.Field;

/**
 * Uses array of arguments (usually passed from cmdline) and an object
 * filled with @ParamArg fields, and then tries to fill in proper object
 * type into those fields.
 * <p/>
 * Does not try to be a smartass in case of wrong type - just crashes horribly.
 *
 * @author deus
 * @version 1.0
 * @since Jul 6, 2010 3:18:18 PM
 */
public final class ParamProcessor {
  private static final Logger LOGGER = Logger.getLogger(ParamProcessor.class);

  private ParamProcessor() {
  }

  public static void configure(Object object, String[] args) throws IllegalAccessException {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
      if (field.getAnnotation(ParamArg.class) == null)
        continue;

      for (String arg : args) {
        if (arg.startsWith("-" + field.getName()))
          processField(object,
              field,
              extractValue(arg));
      }
    }
  }

  private static void processField(Object object, Field field, String stringValue) throws IllegalAccessException {
    PropertyEditor editor = PropertyEditorManager.findEditor(field.getType());
    if (editor == null)
      throw new IllegalStateException("Field config failed: '" + field.getDeclaringClass().getName() + "." + field.getName() + "'.\n" +
          "Unsupported type conversion from string to: " + field.getType());

    editor.setAsText(stringValue);
    field.setAccessible(true);
    field.set(object, editor.getValue());
    field.setAccessible(false);
  }

  private static String extractValue(String arg) {
    return arg.substring(arg.indexOf(':') + 1);
  }
}
